package digital.store.springmvc.controller;

import java.util.Collection;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import digital.store.springmvc.service.CategoryService;
import digital.store.tutorial.springmvc.model.Category;


@Controller
@RequestMapping(value = "/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model) {
        Collection<Category> categories = categoryService.findAll();
        model.addAttribute("categories", categories);
       return "admin/category/list-c";
    }
    
    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String showCreateForm(Model model) {
        model.addAttribute(new Category());

        return "admin/category/create-edit-c";
    }
    
    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    public String showEditForm(@PathVariable Long id, Model model) {
        Category category = categoryService.findById(id);
        model.addAttribute(category);
        return "admin/category/create-edit-c";
    }
    
    @RequestMapping(value="save", method = RequestMethod.POST)
    public String save(@Valid Category category, BindingResult result,HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
        if (result.hasErrors()) {
            return "admin/category/create-edit-c";
        }
        categoryService.saveOrUpdate(category);
        return "redirect:/category/";
    }
    
    @RequestMapping(value="delete", method = RequestMethod.POST)
    public String delete(@RequestParam Long[] id) {
        for (int i = 0; i < id.length; i++) {
            categoryService.delete(id[i]);
        }
        
        return "redirect:/category/";
    }
}
